package com.example.hospitalsystemclient.ui.Prescription;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hospitalsystemclient.Dataclass.MedicineInfo;
import com.example.hospitalsystemclient.Dataclass.PreInfo;
import com.example.hospitalsystemclient.Dataclass.UrlData;
import com.example.hospitalsystemclient.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PreInfoFragment extends Fragment {
    private List<MedicineInfo> medicineList = new ArrayList<>();
    private MedicineAdapter medicineAdapter;
    private UrlData urlData = new UrlData();
    private PreInfo preInfo = new PreInfo();
    private Button payButton;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pre_info, container, false);

        NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_activity_main);
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavigationUI.setupActionBarWithNavController((AppCompatActivity) requireActivity(), navController, appBarConfiguration);

        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("preInfo", 0);
        int preId = sharedPreferences.getInt("preId", -1);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();

        payButton = view.findViewById(R.id.payForPre);

        OkHttpClient client = new OkHttpClient();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("prescriptionId", preId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        Request request = new Request.Builder()
                .url(urlData.showMedicine())
                .post(requestBody)
                .build();
        System.out.println(jsonObject);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "网络问题", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String responseData = response.body().string();
                    try {
                        JSONObject jsonObject = new JSONObject(responseData);
                        if (jsonObject.getBoolean("stat")) {
                            JSONObject dataJSON = jsonObject.getJSONObject("datas");
                            preInfo.setOfficeName(dataJSON.getString("officeName"));
                            preInfo.setDocName(dataJSON.getString("docName"));
                            preInfo.setPrescriptionId(dataJSON.getInt("prescriptionId"));
                            preInfo.setPrescriptionStatement(dataJSON.getInt("prescriptionStatement"));
                            preInfo.setAppointmentTime(dataJSON.getString("appointmentTime"));
                            preInfo.setPrescriptionTime(dataJSON.getString("prescriptionTime"));
                            preInfo.setRecordType(dataJSON.getString("recordType"));
                            preInfo.setDocPhone(dataJSON.getString("docPhone"));
                            preInfo.setDocGender(dataJSON.getString("docGender"));
                            preInfo.setDocAge(dataJSON.getInt("docAge"));
                            preInfo.setRegId(dataJSON.getInt("regId"));
                            preInfo.setRecordResult(dataJSON.getString("recordResult"));
                            if (isAdded())
                                requireActivity().runOnUiThread(() -> {
                                    if (preInfo.getPrescriptionStatement() == 0) payButton.setEnabled(true);
                                    else {
                                        payButton.setEnabled(false);
                                        payButton.setText("已支付");
                                    }
                                });
                            showPreInfo(view);
                        } else {
                            if (isAdded())
                                requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "失败", Toast.LENGTH_SHORT).show());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    if (isAdded())
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "错误！", Toast.LENGTH_SHORT).show());
                }
            }
        });

        OkHttpClient client1 = new OkHttpClient();
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("prescriptionId", preId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject1.toString());
        Request request1 = new Request.Builder()
                .url(urlData.showUnpaidPre())
                .post(requestBody1)
                .build();
        client1.newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "网络问题", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String responseData = response.body().string();
                    try {
                        JSONObject jsonObject = new JSONObject(responseData);
                        System.out.println(jsonObject);
                        if (jsonObject.getBoolean("stat")) {
                            JSONArray dataArray = jsonObject.getJSONArray("datas");

                            for (int i = 0; i < dataArray.length(); i++) {
                                MedicineInfo medicineInfo = new MedicineInfo();
                                JSONObject jsonObject2 = dataArray.getJSONObject(i);
                                medicineInfo.setAmount(jsonObject2.getInt("amount"));
                                medicineInfo.setPrescriptionId(jsonObject2.getInt("prescriptionId"));
                                medicineInfo.setPrescriptionStatement(jsonObject2.getInt("prescriptionStatement"));
                                medicineInfo.setTotalPrice(jsonObject2.getDouble("totalPrice"));
                                medicineInfo.setMedicineId(jsonObject2.getInt("medicineId"));
                                medicineInfo.setSpecification(jsonObject2.getString("specification"));
                                medicineInfo.setRegId(jsonObject2.getInt("regId"));
                                medicineInfo.setState(jsonObject2.getInt("state"));
                                medicineInfo.setDosagePer(jsonObject2.getString("dosagePer"));
                                medicineInfo.setPricePer(jsonObject2.getDouble("pricePer"));
                                medicineInfo.setMedicineName(jsonObject2.getString("medicineName"));
                                medicineInfo.setFrequency(jsonObject2.getString("frequency"));
                                medicineList.add(medicineInfo);
                            }
                            if(isAdded()) requireActivity().runOnUiThread(() -> {
                                TextView totalPrice = view.findViewById(R.id.totalPricePre);
                                totalPrice.setText("总价："+ String.format("%.2f", medicineList.get(0).getTotalPrice()) + "元");
                                medicineAdapter.update(medicineList);
                            });
                        } else {
                            if (isAdded())
                                requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "失败", Toast.LENGTH_SHORT).show());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    if (isAdded())
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "错误！", Toast.LENGTH_SHORT).show());
                }
            }
        });

        // 设置药物列表 RecyclerView
        RecyclerView rvMedicineList = view.findViewById(R.id.rvMedicineList);
        medicineAdapter = new MedicineAdapter(medicineList);
        rvMedicineList.setLayoutManager(new LinearLayoutManager(getContext()));
        rvMedicineList.setAdapter(medicineAdapter);

        payButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OkHttpClient client = new OkHttpClient();
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("prescriptionId", preId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
                Request request = new Request.Builder()
                        .url(urlData.payMedicine())
                        .post(requestBody)
                        .build();
                System.out.println(jsonObject);
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "网络问题", Toast.LENGTH_SHORT).show());
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if (response.isSuccessful()) {
                            final String responseData = response.body().string();
                            try {
                                JSONObject jsonObject = new JSONObject(responseData);
                                if (jsonObject.getBoolean("stat")) {
                                    if (isAdded())
                                        requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "成功支付", Toast.LENGTH_SHORT).show());
                                } else {
                                    if (isAdded())
                                        requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "失败", Toast.LENGTH_SHORT).show());
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            if (isAdded())
                                requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "错误！", Toast.LENGTH_SHORT).show());
                        }
                    }
                });
            }
        });

        return view;
    }

    private void showPreInfo(View view) {
        if (isAdded()) {
            requireActivity().runOnUiThread(() -> {
                TextView tvAppointmentTime = view.findViewById(R.id.tvAppointmentTime);
                TextView tvPrescriptionTime = view.findViewById(R.id.tvPrescriptionTime);
                TextView tvOfficeName = view.findViewById(R.id.tvOfficeName);
                TextView tvDocName = view.findViewById(R.id.tvDocName);
                TextView tvRecordType = view.findViewById(R.id.tvRecordType);
                TextView tvRecordResult = view.findViewById(R.id.tvRecordResult);

                tvAppointmentTime.setText("预约时间: " + preInfo.getAppointmentTime());
                tvPrescriptionTime.setText("开具时间: " + preInfo.getPrescriptionTime());
                tvOfficeName.setText("就诊科室: " + preInfo.getOfficeName());
                tvDocName.setText("就诊医生: " + preInfo.getDocName());
                tvRecordType.setText("就诊类型: " + preInfo.getRecordType());
                tvRecordResult.setText("就诊结果: " + preInfo.getRecordResult());
            });
        }
    }
}